package com.ruoyi.flowable.listener;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.flowable.common.constant.ProcessConstants;
import com.ruoyi.flowable.common.enums.ProcessStatus;
import com.ruoyi.flowable.domain.bo.WfProcessListenerBo;
import com.ruoyi.flowable.domain.vo.WfProcessListenerVo;
import com.ruoyi.flowable.service.IWfProcessListenerService;
import com.ruoyi.flowable.service.ProcessListenerInter;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Flowable 全局监听器
 *
 * @author konbai
 * @since 2023/3/8 22:45
 */
@Component
public class GlobalEventListener extends AbstractFlowableEngineEventListener {

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IWfProcessListenerService iWfProcessListenerService;
    @Autowired
    private ApplicationContext applicationContext;
    /**
     * 流程结束监听器
     */
    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        //流程编号
        String processNo = event.getProcessDefinitionId().split(":")[0];
        WfProcessListenerBo bo = new WfProcessListenerBo();
        bo.setProcessNo(processNo);
        //查出流程编号和监听类的对应关系
        List<WfProcessListenerVo> dataList = iWfProcessListenerService.queryList(bo);
        super.processCompleted(event);
        WfProcessListenerVo vo = dataList.get(0);
        //获取该流程对应的监听类的 路径
        String classPath = vo.getClassPath();
        //后续业务处理逻辑 分发对应得业务监听类
        try{
            ProcessListenerInter listener = (ProcessListenerInter) Class.forName(classPath).newInstance();
            listener.setApplilcation(applicationContext);
            //执行对应业务逻辑
            listener.processCompleted(event);
        }catch(Exception e){
            e.printStackTrace();
            if(classPath == null){
                System.out.println("未发现流程编码 ：" + processNo + "的配置信息");
            }
            else{
                System.out.println("流程监听器：" + classPath + "出错。");
            }

        }
    }
}
